package com.example.educationblockchain.service;

import com.example.educationblockchain.entity.MongoTest;
import com.example.educationblockchain.model.DataBlock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DataBlockService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<DataBlock> findAllDataBlock() {
        return mongoTemplate.findAll(DataBlock.class);
    }

    public List<DataBlock> findDataBlockByHash(String hash) {
        Query query = new Query(Criteria.where("hash").is(hash));
        List<DataBlock> dataBlocks = mongoTemplate.find(query, DataBlock.class);
        return dataBlocks;
    }

    public void deleteDataBlockByHash(String hash){
        Query query = new Query(Criteria.where("hash").is(hash));
        mongoTemplate.remove(query,DataBlock.class);
    }

    public void saveDataBlock(DataBlock dataBlock){
        mongoTemplate.save(dataBlock);
    }

    public void updateDataBlock(DataBlock dataBlock) {
        Query query = new Query();
        query.addCriteria(Criteria.where("hash").is(dataBlock.getHash()));
        Update update = new Update();
        update.set("hash", dataBlock.getHash());
        update.set("dataBlock", dataBlock.getDataBlock());
        mongoTemplate.upsert(query, update, "DataBlock");
    }
}
